/**
 * 
 */
package photosalvage.entity;

import java.util.List;

import javax.inject.Inject;
import javax.persistence.TypedQuery;

import photosalvage.util.JPAUtils;

import com.google.inject.persist.Transactional;

/**
 * @author shumpei
 *
 */
public class AlbumRepository extends BaseRepository<Album, Long> {

	@Inject
	OwnerRepository ownerRepository;
	
	@Transactional
	public List<Album> findByOwner(Long ownerId) {
		TypedQuery<Album> q =
			getEntityManager().createQuery(
					"select a from Album a" +
					" where a.owner.id = :ownerId", Album.class);
		q.setParameter("ownerId", ownerId);
		return q.getResultList();
	}
	@Transactional
	public Album findByNumber(String placeNum, String ownerNum, String albumNum) {
		TypedQuery<Album> q =
			getEntityManager().createQuery(
					"select a from Album a" +
					" where a.owner.place.number = :placeNum" +
					"   and a.owner.number = :ownerNum" +
					"   and a.number = :albumNum", Album.class);
		q.setParameter("placeNum", placeNum);
		q.setParameter("ownerNum", ownerNum);
		q.setParameter("albumNum", albumNum);
		return JPAUtils.getSingleOrNull(q);
	}
	
	@Transactional
	public Album findOrCreateByNumber(String placeNum, String ownerNum, String albumNum) {
		Album a = findByNumber(placeNum, ownerNum, albumNum);
		if (a == null) {
			a = new Album();
			a.setNumber(albumNum);
			Owner owner = ownerRepository.findOrCreateByNumber(placeNum, ownerNum);
			a.setOwner(owner);
			persist(a);
		}
		return a;
	}
}
